const conf = require('./config.json');
const js = require('./jsCtl');
const cc = require('./conCtl');
const db = require('./dbCtl');
const schedule = require('node-schedule');

var AsyncLock = require('async-lock');
const conCtl = require('./conCtl');
var lock = new AsyncLock();

//娃websocket队列
let ctxs = {

};

const userOrderSchedule = {
    item: {}
};



//拍卖缓存对象
// storeAllAuction.auctionList[1].info
const storeAllAuction = {
    auctionList: {//拍卖数据
        auction: {
            info: {},//auction当前拍卖活动数据   todo...修改过名称,待检查执行代码
            curGoods: {},//当前拍卖商品
            goods: {},//即将拍卖商品
        }
    },

}

//九宫格抽奖缓存对象
const storeDial = {
    gameList: { //games  todo...修改过名称,待检查执行代码
        game: {
            info: {},
            curResult: {}, //当前抽奖结果
            curUser: {}, //当前抽奖人
            users: {},
            prizes: {},//奖品
            winner: {},//中奖用户列表
        }
    }
};
//系统设置及机器人数量
const storeSettings = {
    __initSettings_flag: false,//初始化标记
    robot_auction_freeze: 0,
    dial_min_interval: 0,
    dial_max_interval: 0,
    dial_condition_number: 0,
    dial_condition_number_max: 0,
    security_fund: 0,
    robot_count: 0,
};

//初始化系统环境参数
const initSettings = () => {
    return new Promise(async r => {
        await lock.acquire('initSettings', async () => {
            if (storeSettings.__initSettings_flag) {
                r();
                return;
            }
            //获取配置参数
            let setting = await db.model('t_robot_setting').select();
            for (let i = 0; i < setting.length; i++) {
                const elem = setting[i];
                storeSettings[elem.item] = elem.val * 1;
            }

            //获得机器人数量
            storeSettings.robot_count = await db.model('t_robot').count('初始化珠珠儿数量');
            storeSettings.__initSettings_flag = true;
            r();
        });
    });
};
//机器人生产器
const createRobot = (export_id) => {
    return new Promise(async r => {
        //随机获得一个机器人
        let winR = js.randomNum(1, storeSettings.robot_count);
        let robotModel = db.model('t_robot');
        if (export_id) {
            robotModel.whereExtra('id not in (?)', export_id);
        }
        let robotData = await robotModel.select(winR, 1);
        if (robotData.length) {
            r(robotData[0]);
        }
        else {
            r(null);
        }
    });
};

//每天零点零分零秒修改用户15天为收货的订单状态
(async () => {
    //创建定时器
    userOrderSchedule.item = schedule.scheduleJob('00 00 01 * * *', async () => {
        cc.log('开始自动收货');
        await db.model('t_order').where('state=4&&dt<DATE_SUB(CURDATE(), INTERVAL - 15 DAY)').update({ state: 5 });
    });
})();


module.exports = {
    ctxs,
    storeAllAuction,
    storeDial,
    storeSettings,
    initSettings,
    createRobot,
};